import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf  # 导入 TF 库


def himmelblau(x):
    # himmelblau 函数实现，传入参数 x 为 2 个元素的 List
    return (x[0] ** 2 + x[1] - 11) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2


if __name__ == '__main__':
    x = np.arange(-6, 6, 0.1)  # 可视化的 x 坐标范围为-6~6
    y = np.arange(-6, 6, 0.1)  # 可视化的 y 坐标范围为-6~6
    print('x,y range:', x.shape, y.shape)
    # 生成 x-y 平面采样网格点，方便可视化
    X, Y = np.meshgrid(x, y)
    print('X,Y maps:', X.shape, Y.shape)
    Z = himmelblau([X, Y])  # 计算网格点上的函数值
    fig = plt.figure('himmelblau')
    ax = fig.gca(projection='3d')  # 设置 3D 坐标轴
    ax.plot_surface(X, Y, Z)  # 3D 曲面图
    ax.view_init(60, -30)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    plt.show()

    x = tf.constant([4., 0.])
    for step in range(200):
        with tf.GradientTape() as tape:
            tape.watch([x])
            y = himmelblau(x)
        grads = tape.gradient(y, [x])[0]
        x -= 0.01 * grads
        if step % 20 == 19:
            print('step {}: x = {}, f(x) = {}'
                  .format(step, x.numpy(), y.numpy()))


